package com.java.hohenheim.springplatform.web.service.login;

import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.java.hohenheim.springplatform.data.model.account.LoginParams;
import com.java.hohenheim.springplatform.data.model.account.UserInfoModel;
import com.java.hohenheim.springplatform.db.dao.AccountDAO;
import com.java.hohenheim.springplatform.db.entity.AccountEntity;
import com.java.hohenheim.springplatform.define.ResultCodes;
import com.java.hohenheim.springplatform.exception.PlatformException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author Hohenheim
 * @date 2020/8/16
 * @description 用户名登录
 */
@Component("nameLogin")
@Slf4j
public class UserNameLogin extends BaseLogin {
    @Autowired
    private AccountDAO mAccountDAO;

    @Override
    public UserInfoModel login(LoginParams param) {
        checkAccountAndPwdIsBlank(param);

        QueryWrapper<AccountEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", param.getAccount())
                    .eq("pwd", MD5.create().digestHex(param.getPassword()));

        AccountEntity entity = mAccountDAO.getOne(queryWrapper, false);
        if(null == entity) {
            throw new PlatformException(ResultCodes.ACCOUNT_OR_PWD_ERROR);
        }

        UserInfoModel userInfoModel = new UserInfoModel();
        BeanUtils.copyProperties(entity, userInfoModel);
        return userInfoModel;
    }
}
